#include "stationitem.h"
#include "ui_stationitem.h"
#define ASMORDERDBSTR ConnectPoolFactory::getInstance()->getConnectPool(ConnectPoolFactory::AsmOrderDataBase)

stationItem::stationItem(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::stationItem)
{
    ui->setupUi(this);
    qRegisterMetaType<QMap<QString,deviceI>>("QMap<QString,deviceI>");

    stationItemInit();     //接驳台站点初始化

    stationTimer = new QTimer(this);
    connect(stationTimer,&QTimer::timeout,this,&stationItem::ON_stationTimer);
    stationTimer->start(1000);

}

stationItem::~stationItem()
{
    delete ui;
}

void stationItem::stationItemInit()
{

    Udp_DeviceI=new Udp_Device;
    Udp_DeviceI->setListen(9003);
    threadUdpItem=new QThread();
    Udp_DeviceI->moveToThread(threadUdpItem);
    threadUdpItem->start();
    connect(Udp_DeviceI,&Udp_Device::sigDeviceStatuschage,this,&stationItem::ON_stationItemStatus);

    TcpServerI=new TcpServer;
    TcpServerI->listen(QHostAddress::Any,9002);
    threadTcpServertem=new QThread();
    TcpServerI->moveToThread(threadTcpServertem);
    threadTcpServertem->start();
    connect(TcpServerI,&TcpServer::sigDeviceStatuschage,this,&stationItem::ON_stationItemStatus);

    table_single::GetInstance()->TableWidgetInit(ui->tableWidget,12,"QHeaderView::section{background-color:rgb(193,205,205);font:12pt '宋体';color: black;};",25,25);
    connect(ui->tableWidget,&QTableWidget::cellClicked,this,&stationItem::SlotsetCurrentItem);

}

void stationItem::ON_stationTimer()
{
    if(TableWidgetbool){
        TableWidgetbool=false;

        TableWidgetbool=true;
    }
}

void stationItem::SlotsetCurrentItem(int row, int column)
{
    CodeStatus CodeStatusItem;
    currentCodeStatus=CodeStatusItem;
    ui->label_Info->setText("");
    int Station=ui->tableWidget->item(row,0)->text().trimmed().toInt();
    QMap<int,CodeStatus>::iterator iter= CodeStatusMap.begin();
    while (iter!=CodeStatusMap.end()){
        if(iter.value().Station==Station){
            if(iter.value().checked==0){
                iter.value().checked=1;
                currentCodeStatus=iter.value();
            }else {
                iter.value().checked=0;
            }
        }else{
            iter.value().checked=0;
        }
        iter++;
    }
    currentCodeStatus.row=row;
    currentCodeStatus.column=column;
    ui->label_Info->setText(currentCodeStatus.StationDesc);

    ui->label_Info_->setText(currentCodeStatus.StationDesc);
    ui->Room->setText(QString::number(currentCodeStatus.Room));
    ui->Result->setText(QString::number(currentCodeStatus.Result));
    ui->CarCode->setText(QString::number(currentCodeStatus.CarCode));
    ui->CarStauts->setText(QString::number(currentCodeStatus.CarStauts));
    ui->Locked->setText(QString::number(currentCodeStatus.Locked));
    ui->WaitCheck->setText(QString::number(currentCodeStatus.WaitCheck));
    ui->SAPTaskIndex->setText(QString::number(currentCodeStatus.SAPTaskIndex));
    ui->Priority->setText(QString::number(currentCodeStatus.Priority));


    QString label_error="";
    if(currentCodeStatus.Station>0){
        if(currentCodeStatus.Locked==2){
            label_error="禁用";
        }else{
            if(currentCodeStatus.Room==0){
                label_error="位置状态异常";
            }else {
                if(currentCodeStatus.Room==1){//  0表示不确，1表示有车，2表示无车
                    if(currentCodeStatus.CarCode>0){
                        if(currentCodeStatus.CarStauts<=0){
                            label_error="有车架编码，却无车架状态";
                        }if(currentCodeStatus.CarStauts==1){
                            label_error="满车";
                        }if(currentCodeStatus.CarStauts==2){
                            label_error="空车";
                        }
                        if(currentCodeStatus.StationType=="station" && currentCodeStatus.Result==1){
                            label_error="老化好";
                            if(currentCodeStatus.CarStauts!=1){
                                label_error="不是满车,却有老化结果";
                            }
                        }
                    }else{
                        label_error="有车架 却无车编码";
                        if(currentCodeStatus.CarStauts>0){
                            label_error="无车架编码，却有车架状态";
                        }
                    }
                }else{
                    if(currentCodeStatus.StationType=="station" && currentCodeStatus.Result==1){
                        label_error="无车架 却有老化结果";
                    }if(currentCodeStatus.CarCode>0 || currentCodeStatus.CarStauts>0){
                        label_error="无车架 却有车架编码或车架状态";
                    }if(currentCodeStatus.CarCode==0 && currentCodeStatus.CarStauts>0){
                        label_error="无车架编码 却有车架状态";
                    }
                }

                if(currentCodeStatus.Locked==1 || currentCodeStatus.SAPTaskIndex>0){
                    label_error="任务锁定中";
                }

            }

        }
    }

    ui->label_error->setText("当前状态:"+label_error);
    ui->label_Desc->setText("上次更新信息:"+currentCodeStatus.upDateDesc);

    TableWidget_show();

    qDebug()<<" Station:"<<Station<<row<<column<<" -- "<<currentCodeStatus.Station<<ui->checkBox_Edite->isChecked();

}

void stationItem::ON_stationItemStatus(QString DeviceIP, QByteArray ActionArray)
{
    if(!stationbool){return;}
    stationbool=false;

    stationbool=true;
}

void stationItem::ON_DeviceStatusAction(QString DeviceIP, QString deviceType, QString orderType, int Action)
{
    if(deviceType=="station"){
        TcpServerI->setdeviceServerAction(DeviceIP, array_Single::GetInstance()->deviceaction_s(Action));
    }
    qDebug()<<"接驳台动作指令------>DeviceIP:"<<DeviceIP<<" deviceType:"<<deviceType<<" orderType:"<<orderType<<" Action:"<<Action;
}

void stationItem::ON_DeviceStatus(QString deviceDesc, SAPExcelInfo SAPExcelInfoI)
{

}

void stationItem::ON_CodeStatus(QMap<int, CodeStatus> CodeStatusMap_)
{
    if(currentCodeStatus.Station==0 && !ui->checkBox_Edite->isChecked()){
        CodeStatusMap=CodeStatusMap_;
        TableWidget_show();
    }
}

void stationItem::TableWidget_show()
{
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    QList<RW_Excel> ExcelList=TableWidget();
    QStringList comBoxlist;
    table_single::GetInstance()->UP_TableWidget(ui->tableWidget,ExcelList,comBoxlist,0);
    if(ExcelList.isEmpty()){
        ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//列宽根据表格大小自适应
        return;
    }
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//列宽根据表格大小自适应
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::ResizeToContents);

}

QList<RW_Excel> stationItem::TableWidget()
{
    QList<RW_Excel> ExcelList;
    for(int i=0;i<30;i++){
        foreach(CodeStatus iter,CodeStatusMap.values()){
            if(iter.Station==i){
                int incount=0;
                RW_Excel RW_ExcelItem;
                RW_ExcelItem.ExcelA=QString::number(iter.Station);          //站点                                AGV站点，其它老化 房的站点为1－26，上料位为27，下料位为28
                RW_ExcelItem.ExcelB=iter.StationDesc;                       //站点名称
                RW_ExcelItem.ExcelC=QString::number(iter.Room);           //房间状态                             0表示不确，1表示有车，2表示无车
                RW_ExcelItem.ExcelD=QString::number(iter.Result);           //老化结果                             老化完成后此字段会写入1，其他状态写入0

                RW_ExcelItem.ExcelE=QString::number(iter.CarCode);          //车编码
                RW_ExcelItem.ExcelF=QString::number(iter.CarStauts);        //车状态(0未知  1空车架   2满车架)        上料位和下料位由捷思特提供信息，其它位置由AGV自行决定。
                RW_ExcelItem.ExcelG=QString::number(iter.Locked);           //锁定(0解锁  1锁定   2满车架)           有任务时 AGV会锁定
                RW_ExcelItem.ExcelH=QString::number(iter.WaitCheck);        //等待放行状态   0空闲 1AGV等待放行     2MES写入放行  0空闲
                RW_ExcelItem.ExcelI=QString::number(iter.Priority);         //优先出 优先级为1 的

                RW_ExcelItem.ExcelJ=QString::number(iter.SAPTaskIndex);     //站点名称 SAPTaskIndex=0;          //任务索引 唯一值
                RW_ExcelItem.ExcelK= QString::number(iter.agvNum);          //站点名称 agvNum=0;                //小车号

                RW_ExcelItem.ExcelL=iter.statusTimer.toString("MM-dd hh:mm:ss");  //更新时间

                RW_ExcelItem.checked=iter.checked;

                if(incount==0){
                    incount=1;
                    ExcelList.append(RW_ExcelItem);
                }
            }
        }
    }

    return ExcelList;
}

void stationItem::on_load_clicked()
{
    if(!ui->label_Info->text().isEmpty()){
        //TcpServerI->setdeviceServerAction(currentStation.deviceIP, array_Single::GetInstance()->deviceaction_s(1));
    }
}

void stationItem::on_unload_clicked()
{
    if(!ui->label_Info->text().isEmpty()){
        //TcpServerI->setdeviceServerAction(currentStation.deviceIP, array_Single::GetInstance()->deviceaction_s(2));
    }
}

void stationItem::on_reset_clicked()
{
    if(!ui->label_Info->text().isEmpty()){
        //TcpServerI->setdeviceServerAction(currentStation.deviceIP,array_Single::GetInstance()->deviceaction_plc(0));
    }
}

void stationItem::on_clearButton_clicked()
{
    CodeStatus CodeStatusItem;
    currentCodeStatus=CodeStatusItem;
    ui->checkBox_Edite->setChecked(false);
    ui->label_Info_->setText(currentCodeStatus.StationDesc);
    ui->Room->setText(QString::number(currentCodeStatus.Room));
    ui->Result->setText(QString::number(currentCodeStatus.Result));
    ui->CarCode->setText(QString::number(currentCodeStatus.CarCode));
    ui->CarStauts->setText(QString::number(currentCodeStatus.CarStauts));
    ui->Locked->setText(QString::number(currentCodeStatus.Locked));
    ui->WaitCheck->setText(QString::number(currentCodeStatus.WaitCheck));
    ui->SAPTaskIndex->setText(QString::number(currentCodeStatus.SAPTaskIndex));
    ui->Priority->setText(QString::number(currentCodeStatus.Priority));

    ui->label_error->setText("当前状态:");
    ui->label_Desc->setText("上次更新信息:"+currentCodeStatus.upDateDesc);
}

void stationItem::on_pushButton_clicked()
{
    if(ui->checkBox_Edite->isChecked()){
        if(currentCodeStatus.Station>0){
            currentCodeStatus.Room=ui->Room->text().trimmed().toInt();
            currentCodeStatus.Result=ui->Result->text().trimmed().toInt();
            currentCodeStatus.CarCode=ui->CarCode->text().trimmed().toInt();
            currentCodeStatus.CarStauts=ui->CarStauts->text().trimmed().toInt();
            currentCodeStatus.Locked=ui->Locked->text().trimmed().toInt();
            currentCodeStatus.WaitCheck=ui->WaitCheck->text().trimmed().toInt();
            currentCodeStatus.SAPTaskIndex=ui->SAPTaskIndex->text().trimmed().toInt();
            currentCodeStatus.Priority=ui->Priority->text().trimmed().toInt();

            UP_DeviceStatus_clear(currentCodeStatus);
        }
        on_clearButton_clicked();
    }else{
        queryServer::getInstance()->SetMessagebox("请勾选编辑按钮");
    }

}

void stationItem::UP_DeviceStatus_clear(CodeStatus CodeStatusI)
{
    connectBuilder build(ASMORDERDBSTR);
    QSqlDatabase sqlDatabase =  build.getOpenDatabase();
    QSqlQuery sqlQuery(sqlDatabase);

    QString upDateDesc="-- Locked:"+QString::number(CodeStatusI.Locked)
            +" SAPTaskIndex:"+QString::number(CodeStatusI.SAPTaskIndex)
            +" agvNum:"+QString::number(CodeStatusI.agvNum)
            +" CarCode:"+QString::number(CodeStatusI.CarCode)
            +" CarStauts:"+QString::number(CodeStatusI.CarStauts);

    sqlQuery.prepare("UPDATE [dbo].[CodeStatus] SET [Room]=:Room,[Result]=:Result,"
                     "[CarCode]=:CarCode,[CarStauts]=:CarStauts,[Locked]=:Locked,"
                     "[WaitCheck]=:WaitCheck,[SAPTaskIndex]=:SAPTaskIndex,[Priority]=:Priority,"
                     "[upDateDesc]=:upDateDesc,[statusTimer]=:statusTimer "
                     "WHERE [Station]=:Station;");

    sqlQuery.addBindValue(CodeStatusI.Room);            //房间状态                             0表示不确，1表示有车，2表示无车
    sqlQuery.addBindValue(CodeStatusI.Result);          //老化结果                             老化完成后此字段会写入1，其他状态写入0
    sqlQuery.addBindValue(CodeStatusI.CarCode);         //车编码
    sqlQuery.addBindValue(CodeStatusI.CarStauts);       //车状态(0未知  1空车架   2满车架)
    sqlQuery.addBindValue(CodeStatusI.Locked);          //锁定(0解锁  1锁定   2满车架)
    sqlQuery.addBindValue(CodeStatusI.WaitCheck);       //等待放行状态   0空闲 1AGV等待放行     2MES写入放行  0空闲
    sqlQuery.addBindValue(CodeStatusI.SAPTaskIndex);    //任务索引 唯一值
     sqlQuery.addBindValue(CodeStatusI.Priority);       //优先出 优先级为1 的
    sqlQuery.addBindValue(upDateDesc);
    sqlQuery.addBindValue(QDateTime::currentDateTime()); //在卸货点 超时默认完成

    sqlQuery.addBindValue(CodeStatusI.Station);         //站点

    if(sqlQuery.exec()){
        qDebug()<<"UP_DeviceStatus_clear S--->Station"<<CodeStatusI.Station<<" CarCode:"<<CodeStatusI.CarCode<<" CarStauts:"<<CodeStatusI.CarStauts
               <<" Locked:"<<CodeStatusI.Locked<<" WaitCheck:"<<CodeStatusI.WaitCheck<<" SAPTaskIndex:"<<CodeStatusI.SAPTaskIndex;
    }else {
        qDebug()<<"UP_DeviceStatus_clear E--->Station"<<CodeStatusI.Station<<" CarCode:"<<CodeStatusI.CarCode<<" CarStauts:"<<CodeStatusI.CarStauts
               <<" Locked:"<<CodeStatusI.Locked<<" WaitCheck:"<<CodeStatusI.WaitCheck<<" SAPTaskIndex:"<<CodeStatusI.SAPTaskIndex;
    }

}

